#include "wdtx_list.h"

struct listStruct
{
    void* body;
    u16 now;
    u16 length;
    u16 maxLength;
    u8 sizeOfNode;
};

List List_newInstance(u8 sizeOfNode, u16 maxLength)
{
    List list = (List) malloc(sizeof(struct listStruct));
    list->body = malloc(maxLength * sizeOfNode);
    list->length = 0;
    list->maxLength = maxLength;
    list->sizeOfNode = sizeOfNode;
    list->now = 0;
    return list;
}

void List_destroy(List list)
{
    free(list->body);
    list->body = NULL;
    free(list);
}

u16 List_getLength(List list)
{
    return list->length;
}

u16 List_getMaxLength(List list)
{
    return list->maxLength;
}

void List_add(List list, const void* value)
{
    uint32_t target;
    if(list->length >= list->maxLength)
    {
        return;
    }
    target = (uint32_t)list->body;
    target += (list->length)*list->sizeOfNode;
    memcpy((void*)target,value,list->sizeOfNode);
    list->length++;
}

void List_set(List list, u16 position, const void* value)
{
    uint32_t target;
    if(position >= list->maxLength)
    {
        return;
    }
    target = (uint32_t)list->body;
    target += (position)*list->sizeOfNode;
    memcpy((void*)target,value,list->sizeOfNode);
    if(list->length == 0 || position > list->length -1)
    {
        list->length = position +1;
    }
}

void* List_get(List list,u16 position)
{
    if(position > list -> maxLength - 1)
    {
        return NULL;
    }
    return (void*)((uint32_t)list->body + position*list->sizeOfNode);
}

void* List_toArray(List list)
{
    return list->body;
}

void List_moveTo(List list, u16 position)
{
    list->now = position;
}

bool List_hasNext(List list)
{
    if(list->now >= list->maxLength)
    {
        list->now = 0;
        return false;
    }
    else
    {
        return true;
    }
}

void* List_getNext(List list)
{
    return List_get(list,list->now++);
}
